#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <pwd.h>
#include <sys/wait.h>
#define LEN 10

char* Cmd[LEN] = {0};
int count = 0;
char OLDPWD[1024] = {0};
void out_flag()
{
	char flag = '$';
	struct passwd *pw = getpwuid(getuid());
	if(getuid() == 0)
	{
		flag = '#';
	}
	struct utsname host;
	uname(&host);
	char *hostname = strtok(host.nodename, ".");
	char path[128] = {0};
	getcwd(path, 127);//获取当前目录的绝对路径
	char *p = strtok(path, "/");
	char *nowdir = NULL;
	while(p!= NULL)
	{
		nowdir = p;
		p = strtok(NULL, "/");
	}
	if(nowdir == NULL)
	{
		nowdir = "/";
	}
	if(strcmp(nowdir, pw->pw_name) == 0)
	{
		nowdir = "~";
	}
	printf("[%s@%s %s]mybash%c ", pw->pw_name, hostname, nowdir, flag);
	fflush(stdout);
}
void cut_cmd(char *cmd)
{
	char *p = strtok(cmd, " ");
	while(p != NULL)
	{
		Cmd[count++] = p;
		p = strtok(NULL, " ");
	}
}
int special_cmd()
{
	//cd exit 
	if(strncmp("cd", Cmd[0], 2) == 0)
	{
		if(Cmd[1] == NULL || strncmp(Cmd[1], "~", 1) == 0)
		{
			//切换到家目录
			struct passwd *pw = getpwuid(getuid());
			Cmd[1] = pw->pw_dir;
		}
		else if(strncmp(Cmd[1], "-", 1) == 0)
		{
			//切换到家目录到上一次所在目录
			if(strlen(OLDPWD) == 0)
			{
				printf("mybash: cd :: OLDPWD not set\n");
				return 1;
			}
			Cmd[1] = OLDPWD;
			printf("%s\n", Cmd[1]);
		}
		char str[1024] = {0};
		getcwd(str, 1023);
		chdir(Cmd[1]); // 切换路径
		strcpy(OLDPWD, str);
		return 1;
	}
	if(strncmp("exit", Cmd[0], 4) == 0)
	{
		exit(0);
	}
	return 0;
}
void clear_cmd()
{
	int i = 0;
	for(;i < count; ++i)
	{
		Cmd[i] = 0;
	}
	count = 0;
}
void main()
{
	while(1)
	{
		out_flag();
		char cmd[128] = {0};
		fgets(cmd, 128, stdin); //获取命令
		cmd[strlen(cmd) - 1] = 0; //去掉最后一个回车符
		if(strlen(cmd) == 0) // 判别用户的无效输入
		{
			continue;
		}
		cut_cmd(cmd); // 切割cmd
		int res = special_cmd(); // 判别是否是需要集成到bash中的特殊命令
		if(res == 1)
		{
			clear_cmd(); //清空全局的指针数组，并将count归0
			continue;
		}
		pid_t pid = fork();
		assert(pid != -1);
		if(pid == 0)
		{
			// 用命令的可执行文件(./mypwd)替换当前进程
			char path[1024] = "/home/20165223cn/week9/mypwd/";
			if(strstr(Cmd[0], "/") != NULL)
			{
				memset(path, 0, 1024);
			}
			strcat(path, Cmd[0]);
			execv(path, Cmd);
			printf("mybash: %s : command not found\n", Cmd[0]);
			exit(0);
		}
		else
		{
			wait(NULL);
		}
		clear_cmd();
	}
}
